const { CODE_ERROR, CODE_SUCCESS } = require("../config");

//引入mysql操作
const { querySql, queryOne } = require("../utils/query");

exports.publishTest = async (req, res) => {
  const { title, time, attention, items, createTime, submitTimes } = req.body;
  const [startTime, endTime] = time;
  const publishTest = "insert into test set ?";
  const v = await querySql(publishTest, {
    title,
    startTime,
    endTime,
    attention,
    createTime,
    submitTimes,
  });
  if (v.affectedRows == 1) {
    items.forEach(item => {
      item.testId = v.insertId;
      item.contentPic = JSON.stringify(item.contentPic);

      item.resultExamplePic = JSON.stringify(item.resultExamplePic);
      item.file = JSON.stringify(item.file);
    });
    //将数组转化为二维数组(批量添加数据)
    const flat = items.reduce((pre, cur) => {
      pre.push(Object.values(cur));
      return pre;
    }, []);
    const ban = Object.keys(items[0]).join(",");
    const sqlInsertTestDetail = `insert into testDetail(${ban}) VALUES ?`;
    const v1 = await querySql(sqlInsertTestDetail, [flat]);
    if (v1.affectedRows == items.length) {
      res.json({ code: CODE_SUCCESS, msg: "发布成功" });
    } else {
      res.json({ code: CODE_ERROR, msg: "请求失败" });
    }
  } else {
    res.json({ code: CODE_ERROR, msg: "请求失败" });
  }
};
exports.getTestList = async (req, res) => {
  const getList = "select * from test where isDelete=? order by createTime DESC";
  const v = await querySql(getList, 0);
  v.forEach(item => {
    const time = Date.now();
    if (item.startTime > time) {
      item.isDone = -1;
    } else if (item.startTime < time && item.endTime > time) {
      item.isDone = 0;
    } else {
      item.isDone = 1;
    }
  });
  res.json({
    code: CODE_SUCCESS,
    msg: "请求成功",
    data: v,
  });
};
exports.deleteTest = async (req, res) => {
  const id = req.params.id;
  const deleteTest = "update test set isDelete=1 where id=?";
  const v = await querySql(deleteTest, id);
  if (v.affectedRows == 1) {
    res.json({ code: CODE_SUCCESS, msg: "删除成功" });
  } else {
    res.json({ code: CODE_ERROR, msg: "删除失败" });
  }
};
exports.getTestDetailList = async (req, res) => {
  const info = req.query;
  const getTestTime = "select endTime,startTime,submitTimes from test where id=?";
  const time = await queryOne(getTestTime, info.testId);

  const find =
    "select isCommitted, isChecked,submitTimes, testId,score from testMsg where testId=? and userId=?";
  const vt = await queryOne(find, [info.testId, info.id]);
  // console.log(vt);
  if (vt) {
    const sql =
      "select b.id,a.id as testDetailId,a.itemTitle,a.itemContent,a.contentPic,a.resultExample,a.resultExamplePic,a.file,b.reply,b.answer,b.objection,b.answerFile,b.getScore,a.score from student_admin.testDetail as a left join student_admin.testDetailMsg as b on a.id=b.testDetailId where a.testId=? and b.userId=?";
    const v = await querySql(sql, [info.testId, info.id]);
    if (v.length != 0) {
      // console.log(v);
      v.forEach(item => {
        item.file = JSON.parse(item.file) || [];
        item.contentPic = JSON.parse(item.contentPic) || [];
        item.resultExamplePic = JSON.parse(item.resultExamplePic) || [];
        item.answerFile = JSON.parse(item.answerFile) || [];
      });
      const state = {
        isCommitted: vt.isCommitted,
        isChecked: vt.isChecked,
        submitTimes: vt.submitTimes,
      };
      res.json({ code: CODE_SUCCESS, msg: "请求成功", data: { time, list: v, state } });
    } else {
      res.json({ code: CODE_ERROR, msg: "请求失败" });
    }
  } else {
    const sql =
      "select id as testDetailId,itemTitle,itemContent,contentPic,resultExample,resultExamplePic,file,score from testDetail  where testId=?";
    const v = await querySql(sql, [info.testId]);
    if (v.length) {
      // console.log(v);
      v.forEach(item => {
        item.file = JSON.parse(item.file) || [];
        item.contentPic = JSON.parse(item.contentPic) || [];
        item.resultExamplePic = JSON.parse(item.resultExamplePic) || [];
        item.getScore = 0;
        item.reply = "";
        item.answerFile = [];
        item.answer = "";
        item.objection = "";
      });
      const state = { isCommitted: 0, isChecked: 0, submitTimes: time.submitTimes };
      res.json({ code: CODE_SUCCESS, msg: "请求成功", data: { time, list: v, state } });
    } else {
      res.json({ code: CODE_ERROR, msg: "请求失败" });
    }
  }
};
exports.submitTest = async (req, res) => {
  const { userId, list, testId } = req.body;
  const getSubmitTimes = "select submitTimes from test where  id=?";
  const vTimes = await queryOne(getSubmitTimes, [testId]);
  // console.log(vTimes);
  if (vTimes.submitTimes == 0) {
    return res.json({ code: CODE_ERROR, msg: "提交次数已达上限" });
  }
  list.forEach(item => {
    item.userId = userId;
    item.answerFile = JSON.stringify(item.answerFile);
  });
  const flat = list.reduce((pre, cur) => {
    pre.push(Object.values(cur));
    return pre;
  }, []);
  const ban = Object.keys(list[0]).join(",");
  const testDetailMsg = `insert into testDetailMsg(${ban}) values ?`;
  const v = await querySql(testDetailMsg, [flat]);
  if (v.affectedRows == list.length) {
    const testMsg = "insert into testMsg set ?";
    // console.log(testId, vTimes);
    const now = Date.now()
    const v1 = await querySql(testMsg, [{ testId, userId, submitTimes: vTimes.submitTimes - 1 ,updateTime: now}]);
    // console.log(v1);
    if (v1.affectedRows == 1) {
      res.json({ code: CODE_SUCCESS, msg: "提交成功" });
    } else {
      res.json({ code: CODE_ERROR, msg: "提交失败" });
    }
  } else {
    res.json({ code: CODE_ERROR, msg: "提交失败" });
  }
};
exports.resubmitTest = async (req, res) => {
  const { list, userId, testId } = req.body;
  const getSubmitTimes = "select submitTimes from testMsg where userId=? and testId=?";
  const vh = await queryOne(getSubmitTimes, [userId, testId]);
  if (vh.submitTimes <= 0) {
    return res.json({ code: CODE_ERROR, msg: "提交次数已达上限" });
  }
  list.forEach(item => {
    item.answerFile = JSON.stringify(item.answerFile);
  });
  const flat = list.reduce((pre, cur) => {
    pre.push(Object.values(cur));
    return pre;
  }, []);
  const ban = Object.keys(list[0]).join(",");
  const testDetailMsg = `INSERT INTO testDetailMsg(${ban}) VALUES ? ON DUPLICATE KEY UPDATE answer=values(answer),answerFile=values(answerFile)`;
  const v = await querySql(testDetailMsg, [flat]);
  if (v.affectedRows !== 0) {
    const t = "update testMsg set submitTimes=submitTimes-1,updateTime=? where userId=? and testId=?";
    const now = Date.now()
    const tResult = await querySql(t, [now,userId, testId]);
    if (tResult.affectedRows != 0) res.json({ code: CODE_SUCCESS, msg: "提交成功" });
    else res.json({ code: CODE_ERROR, msg: "提交失败" });
  } else {
    res.json({ code: CODE_ERROR, msg: "提交失败" });
  }
};

exports.getCheckTest = async (req, res) => {
  const id = req.params.id;
  const sql =
    "select a.id,a.username,a.realName,b.isCommitted,b.isChecked,b.score,b.submitTImes,b.updateTime,b.testId  from student_admin.user as a left join student_admin.testMsg as b on a.id=b.userId where  b.testId=? and a.isDelete<>1 order by b.updateTime DESC";
  const v = await querySql(sql, id);
  if(Array.isArray(v)){
    res.json({code:CODE_SUCCESS,msg:'获取成功',data:v})
  }else {
    res.json({ code: CODE_ERROR, msg: "获取失败" });
  }
};
exports.giveScore = async (req, res) => {
  const { list, userId, testId } = req.body;
  const flat = list.reduce((pre, cur) => {
    pre.push(Object.values(cur));
    return pre;
  }, []);
  const ban = Object.keys(list[0]).join(",");
  const testDetailMsg = `INSERT INTO testDetailMsg(${ban}) VALUES ? ON DUPLICATE KEY UPDATE getScore=values(getScore)`;
  const v = await querySql(testDetailMsg, [flat]);
  if (v.affectedRows !== 0) {
    const allScore = list.reduce((pre,cur)=>{
      pre = pre+cur.getScore
      return pre
    },0)
    const t = "update testMsg set score=?,isChecked=? where userId=? and testId=?";
    const tResult = await querySql(t, [allScore,1,userId, testId]);
    // console.log(tResult);
    if (tResult.affectedRows != 0) res.json({ code: CODE_SUCCESS, msg: "提交成功" });
    else res.json({ code: CODE_ERROR, msg: "提交失败" });
  } else {
    res.json({ code: CODE_ERROR, msg: "提交失败" });
  }


};
